package com.gitee.mp.core.interceptor;

import cn.hutool.core.collection.CollUtil;
import com.gitee.mp.domain.condition.ConditionBuilder;
import com.gitee.mp.domain.condition.ConditionResult;
import com.gitee.mp.infra.constants.MilvusPlusConstants;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author hongda.li
 */
public class BatchDeleteInterceptor extends AbstractMapperInterceptor {

    @Override
    public boolean supported(Method method) {
        return MilvusPlusConstants.MethodName.METHOD_BATCH_DELETE.equals(method.getName());
    }

    @Override
    public void intercept(InterceptorContext context) {
        Object first = CollUtil.getFirst(context.getArguments());

        if (first instanceof ConditionBuilder<?>) {
            this.interceptByExpression(context);
        } else {
            // 当主键为空时，不允许通过其它非主键删除，防止数据误删
            this.interceptByPrimaryKey(context);
        }
    }

    private void interceptByPrimaryKey(InterceptorContext context) {
        List<?> toDeleteList = (List<?>) CollUtil.getFirst(context.getArguments());
        if (CollectionUtils.isEmpty(toDeleteList)) {
            context.setResult(0);
            return;
        }

        List<Object> primaryKeyList = this.getPrimaryKeyList(context, toDeleteList);

        context.setResult(context.getConnector().delete(this.getCollectionName(context),
                null,
                primaryKeyList));
    }

    private void interceptByExpression(InterceptorContext context) {
        ConditionBuilder<?> builder = (ConditionBuilder<?>) CollUtil.getFirst(context.getArguments());
        ConditionResult condition = builder.build(context.getDefinition().getFieldDefinitionList());

        context.setResult(context.getConnector().delete(this.getCollectionName(context),
                condition.getExpression(),
                null));
    }
}
